import 'package:contract_manager/router/app_pages.dart';
import 'package:contract_manager/utils/authentication.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final rememberMe = false.obs;

  Future<void> login(GlobalKey<FormState> loginFormKey) async {
    if (!loginFormKey.currentState!.validate()) {
      return;
    }

    final username = usernameController.text;
    final password = passwordController.text;

    try {
      await Authentication.authenticate(username, password);
      if (rememberMe.value) {
        // TODO: 保存登录状态
      }
      Get.offAllNamed(AppRoutes.Home);
    } catch (e) {
      Get.snackbar('登录失败', e.toString());
    }
  }

  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}
